import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'

// 添加登录页面导入
import LoginView from '../views/LoginView.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/home'  // 根路径重定向到 /home
    },
    {
      path: '/home',
      name: 'home',
      component: HomeView,
      meta: { requiresAuth: true }  // 需要登录
    },
    {
      path: '/about',
      name: 'about',
      component: () => import('../views/AboutView.vue'),
      meta: { requiresAuth: true }  // 假设 about 也需要登录
    },
    {
      path: '/login',
      name: 'login',
      component: LoginView
    },
  ],
})

// 添加路由守卫
router.beforeEach((to, from, next) => {
  const isLoggedIn = !!localStorage.getItem('token')  // 检查 token
  if (to.meta.requiresAuth && !isLoggedIn) {
    next('/login')  // 未登录跳转到登录页
  } else {
    next()  // 已登录或不需要登录，继续
  }
})

export default router
